<template>
	<view class="payment">
		<u-navbar ref="navbarRef" class="van-nav-bar" :placeholder="true" title="订单详情" @leftClick="leftClick" :autoBack="false"></u-navbar>
		<view class="cantainer" :style="{ height: domHeight }">
			<scroll-view class="scrollWrap" :enhanced="true" scroll-y :bounces="false" :show-scrollbar="false">
				<view class="dot-show" @click="goDotDetail">
					<image :src="$fullImageUrl(experInfo.avatarUrl)"></image>
					<view>
						<view>{{ experInfo.expertName }}</view>
						<view>{{ experInfo.title }}</view>
						<view>{{ experInfo.tags }}</view>
					</view>
					<!-- <view>正在预约中</view> -->
				</view>
				<view class="appointInfo">
					<view>预约信息</view>
					<view class="info">
						<view>服务名称:</view>
						<view v-if="dataObj.consultationType == 1">个人用户个体咨询</view>
						<view v-if="dataObj.consultationType == 2">个人用户家庭咨询</view>
					</view>
					<view class="info">
						<view>咨询方式:</view>
						<view v-if="dataObj.consultationMethod == 1">电话咨询</view>
						<view v-if="dataObj.consultationMethod == 2">线上语音</view>
						<view v-if="dataObj.consultationMethod == 3">线上视频</view>
						<view v-if="dataObj.consultationMethod == 4">当面咨询</view>
					</view>
					<view class="info">
						<view>咨询日期:</view>
						<view>{{ dataObj.appointmentDate }}</view>
					</view>
					<view class="info">
						<view>咨询时间:</view>
						<view>{{ dataObj.startTime }}-{{ dataObj.endTime }}</view>
					</view>
					<view class="info">
						<view>咨询时长:</view>
						<view>{{ calculateTimeDifference(`${dataObj.startTime}-${dataObj.endTime}`) }}</view>
					</view>
					<view class="info">
						<view>来访者:</view>
						<view>{{ personInfo.recordName }}</view>
					</view>
					<view class="info">
						<view>问题类型:</view>
						<view>{{ experInfo.domainName }}</view>
					</view>
					<view class="info">
						<view>咨询费:</view>
						<view>{{ dataObj.amount }}</view>
					</view>
				</view>
				<view class="appointInfo">
					<view>订单信息</view>
					
					<view class="info">
						<view>订单编号:</view>
						<view>{{ dataObj.orderNo }}</view>
					</view>
					<view class="info">
						<view>创建时间:</view>
						<view>{{ dataObj.createTime }}</view>
					</view>
					<view class="info" v-if="dataObj.payNo">
						<view>支付编号:</view>
						<view>{{ dataObj.payNo }}</view>
					</view>
					<view class="info" v-if="dataObj.paymentTime">
						<view>支付时间:</view>
						<view>{{dataObj.paymentTime}}</view>
					</view>
					<view class="info" v-if="dataObj.refundAmount">
						<view>退款金额:</view>
						<view>{{ dataObj.refundAmount }}</view>
					</view>
					<view class="info" v-if="dataObj.refundTime">
						<view>退款时间:</view>
						<view>{{dataObj.refundTime}}</view>
					</view>
					<view class="info" v-if="department_phone">
						<view>联系电话:</view>
						<view>{{department_phone}}</view>
					</view>
				</view>
				<view style="height: 166rpx;"  v-if="dataObj.appointmentStatus*1 === 1 || dataObj.appointmentStatus*1 === 2"></view>
				<view ref="botBtn" class="bot-btn" v-if="dataObj.appointmentStatus*1 === 1">
					<view class="cancle" @click="cancleOrder">
						<text>取消订单</text>
					</view>
					<view class="activeBtn" @click="handlePay">
						<text>去支付</text>
						<text>(剩{{timeShow}})</text>
					</view>
				</view>
				<view ref="botBtn" class="bot-btn" v-if="dataObj.appointmentStatus*1 === 2">
					<view>
						<text></text>
					</view>
					<view class="activeBtn" @click="handleRefundAmount">
						<text>取消预约</text>
					</view>
				</view>
			</scroll-view>
			
		</view>
		
	</view>
</template>

<script>
import {appointmentDetail, getExpert, consultationRecord,editAppointment,cancelAppointment } from '@/api/consult/index.js';
import { createRefund } from '@/api/weiPay/index.js';
import {isWithinTwoHours} from '@/utils/common.js'
import {
		getDoc
	} from '@/api/index/index.js'
export default {
	data() {
		return {
			domHeight: '',
			id: '',
			dataObj: {},
			experInfo: {},
			personInfo: {},
			fromPage: '',
			timeShow: '15分0秒',
			orderCreateTime: '', // 订单创建时间戳（毫秒）
			timer: null,
			department_phone:''
		};
	},
	onLoad(options) {
		getDoc({
			dictType: 'department_phone'
		}).then(res => {
			this.department_phone = res.rows[0].dictLabel;	
		})
		this.id = options.id;
		appointmentDetail(this.id).then((res) => {
			this.dataObj = res.data;
			this.orderCreateTime = res.data.createTime;
			if(res.data.appointmentStatus *1 === 1){
				let time = ''
				this.timer = setInterval(()=>{
					time = this.calculateTimeDifferenceCopy(this.orderCreateTime);
					if(time&&time>1000){
						this.timeShow = this.formatMilliseconds(time)
					}else if(time < 1000){
						this.timeShow = '0'
						clearInterval(this.timer);
						this.$u.toast('订单已取消');
						setTimeout(()=>{
							uni.switchTab({
								url:'/pages/consult/index'
							})
						},1000)
					}
				},1000)
			}
			
			//查询专家信息
			getExpert(res.data.expertId).then((res) => {
				this.experInfo = res.data;
			});
			//查询档案
			consultationRecord(res.data.recordId).then((res) => {
				this.personInfo = res.data;
			});
		});

		// const pages = getCurrentPages();
		// if (pages.length > 1) {
		// 	const prevPage = pages[pages.length - 2];
		// 	this.fromPage = prevPage.route;
		// }
	},
	methods: {
		cancleOrder() {
			uni.showModal({
				title: '提示',
				content: '您确定要取消此预约订单吗？',
				success: (res) => {
					if (res.confirm) {
						cancelAppointment({
							id:  this.dataObj.id,
							appointmentStatus: '4'
						}).then((res) => {
							this.$modal.showToast('取消成功');
							setTimeout(() => {
								this.$tab.navigateBack()
							}, 800);
						});
					} else if (res.cancel) {
						// this.$modal.showToast('已取消');
					}
				}
			});
		},
		handleRefundAmount(){
			uni.showModal({
				title: '提示',
				content: '您确定要取消此预约订单并退款吗？',
				success: (res) => {
					if (res.confirm) {
						if(isWithinTwoHours(`${this.dataObj.appointmentDate} ${this.dataObj.startTime}-${this.dataObj.endTime}`)){
							createRefund({
								id: this.dataObj.id,
								appointmentStatus: '6'
							}).then((res) => {
								this.$modal.showToast('预约时间在两个小时之内，请等待后台审核中');
								setTimeout(() => {
									// this.current = 5;
									// this.currentId = 5;
									this.$tab.navigateBack()
								}, 800);
							});
						}else{
							createRefund({
								id: this.dataObj.id,
								appointmentStatus: '6'
							}).then((res) => {
								this.$modal.showToast('退款成功');
								this.$tab.navigateBack()
							});
						}
						
					} else if (res.cancel) {
						// this.$modal.showToast('已取消');
					}
				}
			});
		},
		goDotDetail(){
			this.$tab.navigateTo(`/subset/pages/consult/consultDetail?id=${this.experInfo.id}`);
		},
		handlePay() {
			uni.showLoading({
			  title: '支付中...',
			  mask: true // 防止触摸穿透
			});
			editAppointment({
				id: this.dataObj.id
			}).then((resa) => {
				wx.requestPayment({
					appId: resa.data.appId,
					nonceStr: resa.data.nonceStr,
					package: resa.data.packageVal,
					paySign: resa.data.paySign,
					signType: resa.data.signType,
					timeStamp: resa.data.timeStamp,
					success: (res) => {
						this.$modal.showToast('支付成功');
						uni.hideLoading();
						setTimeout(() => {
							this.$tab.switchTab(`/pages/consult/index`);
						}, 800);
					},
					fail: (err) => {
						this.$modal.showToast('支付失败');
						uni.hideLoading();
					}
				});
			});
		},
		leftClick() {
			this.$tab.navigateBack()
		},
		formatMilliseconds(ms) {
			const totalSeconds = Math.floor(ms / 1000);
			const minutes = Math.floor(totalSeconds / 60);
			const seconds = totalSeconds % 60;
		
			return `${minutes}分${String(seconds).padStart(2, '0')}秒`;
		},
		calculateTimeDifferenceCopy(inputTimeStr) {
			try {
				// 1. 解析输入时间（兼容常见格式）
				// let date = new Date(inputTimeStr.replace(/ /g, 'T') + 'Z'); // 转换为ISO格式并强制UTC解析
		
				// // 2. 验证时间有效性
				// if (isNaN(date)) throw new Error('Invalid date format');
		
				// // 3. 添加15分钟
				// const newDate = new Date(date.getTime() + 15 * 60 * 1000);
		
				// // 4. 获取当前时间戳
				// const now = Date.now();
		
				// // 5. 时间差计算（毫秒）
				// const diff = newDate.getTime() - now;
				
				const target = new Date(inputTimeStr).getTime() + 15 * 60 * 1000;
				const current = Date.now();
				const diff = target - current;
				// console.log('时间差：', target - current); // 应为正值（未超时）或负值（已超时）
		
				// 6. 返回结果判断
				return diff > 0 ? diff : 0;
		
			} catch (error) {
				console.warn('时间计算错误:', error.message);
				return 0; // 异常情况返回0
			}
		},
		calculateTimeDifference(timeRange) {
			// 分割时间段为开始和结束时间
			const [start, end] = timeRange.split('-');
		
			// 将时间转换为分钟数
			const startMinutes = this.convertToMinutes(start);
			const endMinutes = this.convertToMinutes(end);
		
			// 计算时间差（分钟）
			const diff = endMinutes - startMinutes;
		
			// 转换为小时和分钟
			const hours = Math.floor(diff / 60);
			const minutes = diff % 60;
		
			// 构建结果字符串
			let result = '';
			if (hours > 0) {
				result += `${hours}小时`;
			}
			if (minutes > 0) {
				result += `${minutes}分钟`;
			}
		
			return result || '0分钟'; // 处理0分钟的情况
		},
		
		// 辅助函数：将时间字符串转换为分钟数
		convertToMinutes(timeStr) {
			const [hours, mins] = timeStr.split(':').map(Number);
			return hours * 60 + mins;
		},
	},
	mounted() {
		const systemInfo = uni.getSystemInfoSync();
		let statusBarHeight = systemInfo.statusBarHeight || 20;
		// 示例计算公式（具体需根据组件实现调整）
		const height = statusBarHeight + 44 + 'px'; // 状态栏高度 + 导航栏内容高度
		
		this.domHeight = `calc(100% - ${height})`;
		
		
		
	}
};
</script>

<style lang="scss">
.payment {
	width: 100%;
	height: 100%;
	overflow: hidden;
	background-color: rgb(232, 234, 239);
	.cantainer {
		width: 100%;
		margin: auto;
		
		overflow: hidden;

		.scrollWrap {
			width: 100%;
			height: 100%;
			padding: 20rpx 18rpx;
			// padding-bottom: 20rpx;
			box-sizing: border-box;
			.dot-show {
				width: 100%;
				box-sizing: border-box;
				border-radius: 20rpx;
				padding: 30rpx;
				box-sizing: border-box;
				height: 260rpx;
				background-color: #fff;
				position: relative;
				display: flex;

				> image {
					width: 160rpx;
					height: 200rpx;
					border-radius: 10rpx;
				}

				> view:nth-child(2) {
					width: calc(100% - 160rpx);
					padding: 20rpx 0 20rpx 40rpx;
					display: flex;
					flex-wrap: wrap;
					align-content: space-around;

					> view:nth-child(1) {
						width: 100%;
						font-size: 30rpx;
						color: #000;
						font-weight: bold;
					}

					> view:nth-child(2),
					view:nth-child(3) {
						width: 100%;
						font-size: 24rpx;
						color: #a8a8a8;
					}
				}

				// > view:last-child {
				// 	position: absolute;
				// 	right: 0;
				// 	top: 0;
				// 	width: 150rpx;
				// 	height: 60rpx;
				// 	line-height: 60rpx;
				// 	text-align: center;
				// 	font-size: 26rpx;
				// 	background-color: #ffefbf;
				// 	color: #ffaa00;
				// 	border-top-right-radius: 20rpx;
				// }
			}

			.appointInfo {
				width: 100%;
				padding: 40rpx 30rpx;
				margin-top: 20rpx;
				background-color: #fff;
				border-radius: 20rpx;

				> view:first-child {
					width: 100%;
					font-size: 32rpx;
					font-weight: bold;
					color: #000;
				}

				.info {
					width: 100%;
					display: flex;
					margin-top: 40rpx;

					> view {
						font-size: 28rpx;
					}

					> view:nth-child(1) {
						width: 150rpx;
						color: #a8a8a8;
					}

					> view:nth-child(2) {
						width: calc(100% - 150rpx);
						color: #000;
					}
				}
			}
		}
	}
	.bot-btn {
		width: 100%;
		height: 166rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		padding: 30rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	
		.cancle {
			width: 40%;
			height: 106rpx;
			text-align: center;
			line-height: 106rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #e7e7e7;
			color: #2c2c2c;
			font-size: 32rpx;
			border-radius: 50rpx;
		}
	
		>view:last-child {
			width: 50%;
			height: 106rpx;
			text-align: center;
			line-height: 106rpx;
			background: #e7e7e7;
			color: #bcbcbc;
			font-size: 32rpx;
			border-radius: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	
		.activeBtn {
			background: #5c83fd !important;
			color: #fff !important;
		}
	}
}
</style>
